package view.mediators
{
	import flash.events.Event;
	
	import model.LoginProxy;
	
	import org.puremvc.as3.interfaces.IMediator;
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.mediator.Mediator;
	
	import view.Login;
	
	public class LoginMediator extends Mediator implements IMediator
	{
		public static const NAME:String = "Login Mediator";
		public static const ENTER:String = "Enter";
		
		public function LoginMediator(login:Login)
		{
			super(NAME, login);
			login.addEventListener(ENTER, enter);
		}
		
		private function enter(e:Event):void{
			if (login.txtName.text.length == 0){
				login.lblInfo.text = "Please enter your name";
			} else if (login.light.selected == false && login.dark.selected == false){
				login.lblInfo.text = "Please select a side";
			} else{
				login.lblInfo.text = "Attempting to login...";
				if (login.dark){
					proxy.setPlayer(BoardFacade.DARK_SIDE, login.txtName.text);
				} else if (login.light){
					proxy.setPlayer(BoardFacade.LIGHT_SIDE, login.txtName.text);
				}	
			}
		}
		
		protected function get login():Login{
			return viewComponent as Login;
		}
		
		override public function listNotificationInterests():Array{
			return [
					LoginProxy.FIRST_PLAYER_READY,
					LoginProxy.NO_PLAYER_PRESENT,
					LoginProxy.LOGIN_OK
					];
		}
		
		override public function handleNotification(notification:INotification):void{
			switch(notification.getName()){
				case LoginProxy.NO_PLAYER_PRESENT:
					login.lblInfo.text = "Please enter your name and choose a side";
					break;
				case LoginProxy.FIRST_PLAYER_READY:
					login.lblInfo.text = "Player 1 is ready. Please enter your name to join";
					var side = notification.getBody() as String;
					if (side == BoardFacade.DARK_SIDE){
						login.dark.enabled = false;
						login.light.selected = true;
					} else if (side == BoardFacade.LIGHT_SIDE){
						login.light.enabled = false;
						login.dark.selected = true;
					}
					break;
				case LoginProxy.LOGIN_OK:
					sendNotification(BoardFacade.START_BOARD, login.parent);
			}
		}
		
		private function get proxy():LoginProxy{
			return facade.retrieveProxy(LoginProxy.NAME) as LoginProxy;
		}

	}
}